package com.yonyougov.devops.cruxcisupport.component;

import com.yonyougov.devops.cruxcisupport.button.ButtonEntity;
import com.yonyougov.devops.cruxcisupport.button.ButtonService;
import com.yonyougov.devops.cruxcisupport.role.RoleEntity;
import com.yonyougov.devops.cruxcisupport.rolebutton.RoleButtonEntity;
import com.yonyougov.devops.cruxcisupport.rolebutton.RoleButtonService;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.List;

@Component
public class PermissionCheck {
    private UserStore userStore;
    private RoleButtonService roleButtonService;
    private ButtonService buttonService;

    public PermissionCheck(UserStore userStore, RoleButtonService roleButtonService, ButtonService buttonService) {
        this.userStore = userStore;
        this.roleButtonService = roleButtonService;
        this.buttonService = buttonService;
    }

    /***
     * 检查用户是否有按钮的权限
     * @param userId
     * @param menuCode
     * @param buttonCode
     * @return
     */
    public boolean checkButtonPermission(BigInteger userId, String menuCode, String buttonCode) {
        ButtonEntity buttonCond = new ButtonEntity();
        buttonCond.setCode(buttonCode);
        ButtonEntity btn = buttonService.findBy(buttonCond);
        List<RoleEntity> roles = userStore.currentUserRoles();
        for (RoleEntity role : roles) {
            RoleButtonEntity roleButtonCond = new RoleButtonEntity();
            roleButtonCond.setRoleId(role.getId());
            roleButtonCond.setBtnId(btn.getId());
            if (roleButtonService.countBy(roleButtonCond) == 0) {
                return false;
            }
        }
        return true;
    }
}
